﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace MySqlData
{
    public class MySqlHelper
    {
        static MySqlHelper()
        {
            var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

            IConfigurationRoot config = builder.Build();
            ConnectionString = config["ConnectionStrings:CrmMySalConn"];
        }

        public static string ConnectionString = null;


        public static void Query(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(ConnectionString))
            {
                //DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    connection.Close();
                    //command.Fill(ds, "ds");
                }
                catch (Exception ex)
                {
                    connection.Close();
                    throw new Exception(ex.Message);
                }
                //return ds.Tables[0];
            }
        }

        public static DataSet Query_New(string SQLString, string connstr = "")
        {
            connstr = ConnectionString;
            using (MySqlConnection connection = new MySqlConnection(connstr))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    connection.Close();
                    command.Fill(ds, "ds");
                }
                catch (Exception ex)
                {
                    var str = ex;
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }


        public static int ExecuteUpMySql(string sql)
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(ConnectionString))
                {
                    conn.Open();
                    int res;
                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    res = cmd.ExecuteNonQuery();
                    conn.Close();
                    return res;
                }
            }
            catch (Exception e)
            {
                return -1;
            }

        }

    }
}
